<template>
  <el-form
    :model="formData"
    ref="formRef"
    :rules="formRules"
    label-width="80px"
    class="content"
    :validate-on-rule-change="false"
  >
    <el-row>
      <el-col :span="12">
        <el-form-item label="姓名" prop="name">
          <el-input
            :disabled="isEmp === '1'"
            v-model="formData.name"
            class="width-custom"
            autocomplete="off"
          ></el-input> </el-form-item
      ></el-col>
      <el-col :span="12">
        <el-form-item label="邮箱" prop="email">
          <el-input
            :disabled="isEmp === '1'"
            type="email"
            v-model="formData.email"
            class="width-custom"
          ></el-input> </el-form-item
      ></el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="用户名" prop="userName">
          <el-input
            :disabled="isEmp === '1'"
            v-model.trim="formData.userName"
            class="width-custom"
          ></el-input> </el-form-item
      ></el-col>

      <el-col :span="12">
        <el-form-item label="所属公司" prop="companyName">
          <el-select
            v-model="formData.companyName"
            filterable
            placeholder="请选择"
            value-key="companyId"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in companyLists"
              :key="item.companyId"
              :label="item.companyName"
              :value="item"
            >
            </el-option> </el-select></el-form-item
      ></el-col>
      <!-- <el-col :span="12">
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="formData.userType" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in userTypeEnum"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select> </el-form-item
      ></el-col> -->
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="角色" prop="rolesList">
          <el-select
            v-model="formData.rolesList"
            filterable
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleLists"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option> </el-select></el-form-item
      ></el-col>

      <el-col :span="12">
        <el-form-item label="手机号" prop="phoneNum">
          <el-input
            :disabled="isEmp === '1'"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="11"
            v-model.number.trim="formData.phoneNum"
            class="width-custom"
          ></el-input> </el-form-item
      ></el-col>
    </el-row>

    <el-row>
      <el-col>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="formData.remark"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- <el-form-item label="wxCode" prop="wxCode">
      <el-input v-model.trim="formData.wxCode" class="width-custom"></el-input>
    </el-form-item> -->
    <!-- <el-form-item label="所在地区" prop="area">
      <el-input v-model="formData.area" class="width-custom"></el-input>
    </el-form-item> -->
    <!-- <el-form-item label="头像" prop="photo"> </el-form-item> -->
  </el-form>

  <el-row justify="end" class="form__footer">
    <el-button @click="handleSubmit(false)">取 消</el-button>
    <el-button type="primary" @click="handleSubmit(true)">确 定</el-button>
  </el-row>
</template>

<script lang="ts">
import {
  reactive,
  defineComponent,
  ref,
  onMounted,
  PropType,
  toRef,
  toRefs
} from "vue";
import { addUser, updateUser, postUserInfo } from "/@/api/user";
import { roleList } from "/@/api/roles";
import { postSysCompanyList } from "/@/api/organization";
import NotifMessage from "/@/utils/message/notification";
import {
  validatorPhone,
  validatorEmail,
  validatorUserName
} from "/@/utils/validator";
import { clickEvent } from "/@/utils/func";
import { cloneDeep } from "lodash-es";

import { userTypeEnum, ModeType, UserInfoType, RoleListType } from "../types";

export default defineComponent({
  name: "UserDetail",
  props: {
    mode: {
      type: String as PropType<ModeType>,
      require: true,
      default: "add"
    },
    userInfo: {
      type: Object as PropType<UserInfoType>,
      default: () => {}
    },
    companyInfo: {
      type: Object,
      default: () => {}
    }
  },
  emits: ["emitClose"],
  setup(props, { emit }) {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const currentInfo = toRef(props, "userInfo");
    const currentCompanyInfo = toRef(props, "companyInfo");

    let roleLists = ref<RoleListType[]>([]);
    let companyLists = ref([]);
    let isEmp = ref("0");
    let state = reactive({
      formData: {
        address: "",
        age: null,
        area: "",
        companyName: {},
        deviceId: "",
        email: "",
        name: "",
        nickName: "",
        password: "",
        phoneNum: "",
        photo: "",
        userName: "",
        userType: "",
        wxCode: "",
        rolesList: "",
        companyId: null,
        remark: ""
      }
    });

    const formRules = {
      // age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
      email: [{ required: true, validator: validatorEmail, trigger: "blur" }],
      name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      // companyName: [
      //   { required: true, message: "请选择所属公司", trigger: "change" }
      // ],
      rolesList: [{ required: true, message: "请选择角色", trigger: "change" }],
      // password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      phoneNum: [
        { required: true, validator: validatorPhone, trigger: "blur" }
      ],
      userName: [
        { required: true, validator: validatorUserName, trigger: "blur" }
      ],
      userType: [
        { required: true, message: "请选择用户类型", trigger: "change" }
      ]
    };

    // 编辑时获取用户选择的角色
    // const getUserRoles = async (userId: number) => {
    //   if (!userId) return;
    //   try {
    //     const params = {
    //       userId: userId
    //     };
    //     let filterRoles = [];
    //     const { code, data } = await searchRoleAuth(params);
    //     if (code === 200) {
    //       data.forEach(item => {
    //         filterRoles.push(item.id);
    //       });
    //     }
    //     return filterRoles;
    //   } catch (error) {
    //     console.log(error);
    //   }
    // };

    // 确认提交
    const handleSubmit = (isSubmit: boolean): void => {
      if (isSubmit) {
        formRef.value.validate(async (valid: any) => {
          if (valid) {
            // const { companyId, companyName } = state.formData.companyName;
            const companyInfo = cloneDeep(state.formData.companyName);
            state.formData.companyId = companyInfo.companyId;
            state.formData.companyName = companyInfo.companyName;
            // @ts-ignore   后端目前还是多角色配置，所以这里还是数组
            const copyParams = cloneDeep(state.formData);
            copyParams.rolesList = [state.formData.rolesList];
            try {
              if (props.mode === "add") {
                const { code, message } = await addUser(copyParams);
                clickEvent("用户管理", "确定", "新增用户");
                requestSuccess(code, message, isSubmit);
              } else {
                const { code, message } = await updateUser(copyParams);
                clickEvent("用户管理", "确定", "编辑用户");
                requestSuccess(code, message, isSubmit);
              }
            } catch (err) {
              state.formData.companyName = companyInfo;
              // state.formData.rolesList = state.formData.rolesList[0];
            }
          }
          return false;
        });
      } else {
        emit("emitClose", isSubmit);
      }
    };

    // 请求结果统一处理
    const requestSuccess = (
      code: number,
      message: string,
      isSubmit: boolean
    ) => {
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitClose", isSubmit);
      }
    };

    // 请求角色列表数据
    async function getRoleList() {
      const params = { pageSize: 0 };
      const { code, data } = await roleList(params);
      if (code === 200) {
        roleLists.value = data.list;
      }
    }

    // 请求公司列表数据
    async function getCompanyList() {
      const params = { pageSize: 500, pageNum: 1 };
      try {
        const { code, data } = await postSysCompanyList(params);
        if (code === 200) {
          companyLists.value = data.list.map(item => {
            return { companyId: item.id, companyName: item.companyName };
          });
        }
      } catch (err) {
        console.log(err);
      }
    }

    onMounted(() => {
      // 清除表单验证
      formRef.value.clearValidate();
      getRoleList();
      getCompanyList();
      if (props.mode === "edit") {
        getUserInfo(currentInfo.value.id);
        // const copyCurrentInfo = cloneDeep(currentInfo.value);
        // state.formData = copyCurrentInfo;
        // state.formData.companyName = {
        //   companyName: copyCurrentInfo.companyName,
        //   companyId: +copyCurrentInfo.companyId
        // };
        // // state.formData.rolesList = await getUserRoles(copyCurrentInfo.id);
        // state.formData.rolesList = copyCurrentInfo.userRolesList.map(item => {
        //   return item.roleId;
        // })[0];
      } else {
        const copyCurrentCompanyInfo = cloneDeep(currentCompanyInfo.value);
        // 如果公司id 不等于 0，则进行赋值
        if (copyCurrentCompanyInfo.id) {
          state.formData.companyName = {
            companyName: copyCurrentCompanyInfo.companyName,
            companyId: +copyCurrentCompanyInfo.id
          };
        }
      }
    });

    const getUserInfo = async userId => {
      try {
        const params = {
          id: userId
        };
        const { code, data } = await postUserInfo(params);
        if (code === 200) {
          const copyCurrentInfo = cloneDeep(data);
          state.formData = copyCurrentInfo;
          delete state.formData.sysType;
          state.formData.companyName = {
            companyName: copyCurrentInfo.companyName,
            companyId: +copyCurrentInfo.companyId
          };
          // state.formData.rolesList = await getUserRoles(copyCurrentInfo.id);
          state.formData.rolesList = copyCurrentInfo.userRolesList.map(item => {
            return item.roleId;
          })[0];

          // 是否内部员工
          isEmp.value = copyCurrentInfo.isEmp;
        }
      } catch (err) {
        console.log(err);
      }
    };

    return {
      ...toRefs(state),
      roleLists,
      companyLists,
      isEmp,
      // formData,
      userTypeEnum,
      formRef,
      formRules,
      getUserInfo,
      handleSubmit
    };
  }
});
</script>
